package com.yunfei.api.v2.service;
import com.yunfei.api.v2.common.YunHeTongApiContant;
import com.yunfei.api.v2.param.LongTokenParam;
import com.yunfei.api.v2.param.ReserveNoParam;
import com.yunfei.api.v2.param.heTongDownLoad.HeTongDownLoadParam;
import com.yunfei.api.v2.param.heTongLuRu.ContractUpdateParam;
import com.yunfei.api.v2.param.heTongLuRu.HeTongLuRuParam;
import com.yunfei.api.v2.param.heTongSign.HeTongSignParam;
import com.yunfei.api.v2.result.jiaGaiResult.AutoJiaGaiResult;
import com.yunfei.bo.crmAcceDtl.CrmAcceDtlBo;
import com.yunfei.bo.result.ResultModel;
import com.yunfei.contants.ApplicationConstant;
import com.yunfei.contants.AutoJiaGaiConstant;
import com.yunfei.entity.TblobstorageEntity;
import com.yunfei.mapper.aiiidb.AutoJiaGaiZhangMapper;
import com.yunfei.mapper.aiiidb.AutoSubmitContractInfoMapper;
import com.yunfei.mapper.aiiidb.CrmAcceDtlMapper;
import com.yunfei.mapper.crm.AutoTiJiaoContractInfoMapper;
import com.yunfei.mapper.crm.TblobtSorageMapper;
import com.yunfei.procedure.AutoSubmitContractInfoProcedure;
import com.yunfei.procedure.ProcedureResultModel;
import com.yunfei.utils.DateUtil;
import com.yunfei.utils.http.HttpUtils;
import com.yunfei.utils.jdbc.AiiidbUtil;
import com.yunfei.utils.string.StringUtil;
import com.yunfei.yunhetong.elecContOperLog.bo.ElecContOperLogBo;
import com.yunfei.yunhetong.elecContOperLog.service.ElecContOperLogService;
import com.yunfei.yunhetong.heTongSignManager.entity.HeTongSignManagerEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @Description:自动加盖公章定时任务，封装为接口
* @Author: zhengyunfei
* @Date: 2019/8/9
* @time:10:48
*/
@Service
public class AutoAddJiaGaiJobService {
    @Autowired
    private Environment env;
    @Autowired
    private AutoJiaGaiZhangMapper autoJiaGaiZhangMapper;
    @Autowired
    private ElecContOperLogService elecContOperLogService;
    @Autowired
    private ContractSignService contractSignService;
    @Autowired
    private AutoShenHeContractJobService autoShenHeContractJobService;
    @Autowired
    private AutoTiJiaoContractInfoMapper autoTiJiaoContractInfoMapper;
    @Autowired
    private AutoSubmitContractInfoMapper autoSubmitContractInfoMapper;
    @Autowired
    private ContractUpdateService contractUpdateService;
    @Autowired
    private DownLoadContractService downLoadContractService;
    @Autowired
    private TblobtSorageMapper tblobtSorageMapper;
    @Autowired
    private CrmAcceDtlMapper crmAcceDtlMapper;
    @Autowired
    private GetLongTokenService getLongTokenService;
    /**
    * @Description: 自动加盖公章
    * @Author: zhengyunfei
    * @Date: 2019/8/15
    * @time:16:26
    */
    public void run(){
        //定时任务开关
        Object flag=env.getProperty(ApplicationConstant.JOBS_SCHEDULE_OPEN);
        if(ApplicationConstant.TRUE.equals(flag)){
            autoJiaGaiGongZhang();//自动加盖公章

        }
    }
   /**
   * @Description: 自动加盖管理人公章
   * @Author: zhengyunfei
   * @Date: 2019/8/28
   * @time:10:48
   */
    private void autoJiaGaiGongZhang() {
        try{
            Map<String,Object> queryMap=new HashMap<>();
            //获取需要自动加盖公章的数据
            List<AutoJiaGaiResult> list=autoJiaGaiZhangMapper.list(queryMap);
            System.out.println("系统自动加盖管理人公章，定时任务开始执行。。。。。需要执行的条数="+list.size()+",当前时间="+ DateUtil.getDateNow());
            for(int i=0;i<list.size();i++) {
                AutoJiaGaiResult bo = list.get(i);
                String contractId = bo.getContractId();//合同id
                String contractNum = bo.getContractNum();//合同编号
                String magerId = bo.getMagerId();//管理人公章id
                String caCustId = bo.getCaCustId();//管理人用户id
                String agentId = bo.getAgentId();//法定代表人公章id
                String agentUserId = bo.getAgentUserId();//法人用户id
                String reserveNo= bo.getcReserveNo();//预约编号
                //调用合同签署接口-法定代表人签署
                HeTongSignParam faRenParam = new HeTongSignParam();
                faRenParam.setIdType(YunHeTongApiContant.ID_TYPE_DEFAULT);
                faRenParam.setIdContent(contractId);
                faRenParam.setSignerId(agentUserId);
                faRenParam.setMoulageId(agentId);
                faRenParam.setSealClass(YunHeTongApiContant.SET_SEAL_CLASS);//带时间样式的签章
                ResultModel farenResult=contractSignService.sign(faRenParam);
                System.out.println("法定代表人签署===================="+farenResult.getData().toString());
                //调用合同签署接口-管理人签署
                HeTongSignParam heTongSignParam = new HeTongSignParam();
                heTongSignParam.setIdType(YunHeTongApiContant.ID_TYPE_DEFAULT);
                heTongSignParam.setIdContent(contractId);
                heTongSignParam.setSignerId(caCustId);
                heTongSignParam.setMoulageId(magerId);
                heTongSignParam.setSealClass(YunHeTongApiContant.SET_SEAL_CLASS);
                ResultModel managerResult=contractSignService.sign(heTongSignParam);
                System.out.println("管理人签署===================="+managerResult.getData().toString());

                //插入日志表
                ElecContOperLogBo elecContOperLogBo = new ElecContOperLogBo();
                elecContOperLogBo.setContractId(contractId);
                elecContOperLogBo.setContractNum(contractNum);
                elecContOperLogBo.setOperId(AutoJiaGaiConstant.OPER_ID);//默认9999999
                elecContOperLogBo.setOperTyp(AutoJiaGaiConstant.OPER_TYP);//默认加盖管理人公章
                elecContOperLogService.add(elecContOperLogBo);
                //自动提交合同
                autoSubmitContractInfo(contractId,reserveNo);
                //更新合同签署状态
                HeTongSignManagerEntity updateStatusParam=new HeTongSignManagerEntity();
                updateStatusParam.setContractId(contractId);
                updateStatusParam.setContractSts("3");
                contractSignService.updateContractSignStatus(updateStatusParam);
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }
    /**
     * @Description: 系统自动提交合同信息
     * @Author: zhengyunfei
     * @Date: 2019/8/15
     * @time:16:26
     */
    public void autoSubmitContractInfo(String contractId,String reserveNo){
        try{
            System.out.println("系统自动提交合同信息。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。start");
            long starTime=System.currentTimeMillis();
            String lBenSeriAlNo="";
            Map<String,Object> queryMap=new HashMap<>();
            queryMap.put("reserveNo",reserveNo);
             lBenSeriAlNo= (String) autoTiJiaoContractInfoMapper.get(queryMap);
            //如果上面的结果返回的无数据，代表当前预约未录入合同信息，执行新增操作：
            HeTongLuRuParam heTongLuRuParam=null;
            if(StringUtil.isNullOrEmpty(lBenSeriAlNo)){
                heTongLuRuParam= (HeTongLuRuParam) autoSubmitContractInfoMapper.get(queryMap);
                if(!StringUtil.isNullOrEmpty(heTongLuRuParam)){
                    //执行新增操作
                    AutoSubmitContractInfoProcedure autoSubmitContractInfoProcedure=new AutoSubmitContractInfoProcedure();
                    AiiidbUtil aiiidbUtil=AiiidbUtil.getInstance(env);
                    ProcedureResultModel procedureResultModel= autoSubmitContractInfoProcedure.callProcedure(aiiidbUtil,heTongLuRuParam,reserveNo);
                    if(!StringUtil.isNullOrEmpty(procedureResultModel)){
                        lBenSeriAlNo=procedureResultModel.getReturnInfo();
                    }
                }

            }else{
                //执行编辑操作
                ContractUpdateParam contractUpdateParam=ContractUpdateParam.getContractUpdateParam(heTongLuRuParam);
                contractUpdateParam.setlBenserialNo(lBenSeriAlNo);
                contractUpdateService.contractUpdate(contractUpdateParam);
            }
            //上传附件
            //调用api下载电子合同
            if(!StringUtil.isNullOrEmpty(lBenSeriAlNo)){
                downloadContractToCrm(contractId, lBenSeriAlNo);
                long endTime=System.currentTimeMillis();
                long Time=endTime-starTime;
                System.out.println("自动审核合同程序运行时间："+Time);
                //自动审核合同
                autoShenHeContract(lBenSeriAlNo);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //下载电子合同并保存到crm中
    private void downloadContractToCrm(String contractId, String lBenSeriAlNo) {
        HeTongDownLoadParam heTongDownLoadParam=new HeTongDownLoadParam();
        heTongDownLoadParam.setIdContent(contractId);
        heTongDownLoadParam.setIdType("0");
        TblobstorageEntity tblobstorageEntity=downLoadContractService.download(heTongDownLoadParam);
        tblobstorageEntity.setCSubkeyid(lBenSeriAlNo);
        String lStorageId=tblobtSorageMapper.getTblobStorageSeq()+"";
        tblobstorageEntity.setLStorageid(lStorageId);
        //保存附件到crm库tblobstorage表中
        tblobtSorageMapper.add(tblobstorageEntity);
        //保存附件到app库tblobstorage表中
        crmAcceDtlMapper.addTblobstorage(tblobstorageEntity);
        //保存文件附件到app数据库
        CrmAcceDtlBo crmAcceDtlBo=new CrmAcceDtlBo();
        crmAcceDtlBo.setLStorageid(lStorageId);
        String fileUrl=tblobstorageEntity.getCFilepath();
        crmAcceDtlBo.setFileUrl(fileUrl);
        crmAcceDtlMapper.add(crmAcceDtlBo);
        //将远程文件存到crm中
        //获取当前环境
        String active=env.getProperty(ApplicationConstant.DEBUG);
        String crmBootServiceDomain="";
        if(active.contains(ApplicationConstant.DEBUG_VALUE)){
            //生产环境
            crmBootServiceDomain=ApplicationConstant.PROD_CRM_BOOT_SERVICE;
        }else{
            //测试环境
            crmBootServiceDomain=ApplicationConstant.TEST_CRM_BOOT_SERVICE;
        }
        String url=crmBootServiceDomain+"/api/v2/file//syncToCrm";
        Map<String,String> uploadToCrmParam=new HashMap<>();
        uploadToCrmParam.put("lStorageId",lStorageId);
        uploadToCrmParam.put("fileUrl",fileUrl);
        HttpUtils.sendPost(url,uploadToCrmParam);
    }

    /**
     * @Description: 自动审核合同
     * @Author: zhengyunfei
     * @Date: 2019/8/28
     * @time:10:48
     */
    private void autoShenHeContract(String lBenserialNo) {
        try{
            //自动审核合同
            System.out.println("自动审核合同。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。start");
            long starTime=System.currentTimeMillis();
            autoShenHeContractJobService.run(lBenserialNo);
            long endTime=System.currentTimeMillis();
            long Time=endTime-starTime;
            System.out.println("自动审核合同程序运行时间："+Time);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
